import Vue from 'vue'
import Vuex from 'vuex'
import store from '../store'
let vue = Vue.use(Vuex)

function isNotEmpty(row, column) {
  return row.hasOwnProperty(column.property)
    && row[column.property] != null
    && row[column.property] != undefined
    && row[column.property] != ""
}

export default class thiss {
  constructor(options) {
  }

  getRolesColumns(){
    return [
      { prop: 'name', label: '角色', fixed: true, sortable: true, width: '270', formatter: this.stringFormater },
      { prop: 'query', label: '数据授权', sortable: true, width: '320', formatter:this.dataPrivFormatter},
      { prop: 'roles', label: '功能授权', width: '380', sortable: true, formatter: this.funcPrivFormatter}
    ]
  }

  dataPrivFormatter(row, column){
    if (isNotEmpty(row, column)) {
      var dataPriv = row[column.property]
      switch(dataPriv){
        case 0:
          return '限看本人数据'
        case 1:
          return '限查看本部门数据'
        case 2:
          return '限查看除中心领导外数据'
        case 3:
          return '允许查看所有数据'
      }
    }
    return ''
  }

  funcPrivFormatter(row, column){
    var funcDesc='基础权限'
    if (isNotEmpty(row, column)) {
      var funcPriv = row[column.property]
      // 有增加删除修改权限
      if(funcPriv & 1){
        funcDesc = funcDesc + ',修改权限'
      }
      // 有审核权限
      if(funcPriv & 2){
        funcDesc = funcDesc + ',审核权限'
      }
      // 有系统管理权限
      if(funcPriv & 4){
        funcDesc = funcDesc + ',管理权限'
      }
      // 有首页权限
      if(funcPriv & 8){
        funcDesc = funcDesc + ',首页权限'
      }
    }
    return funcDesc
  }
  
  getOnJobUsersColumns(){
    return [
      { prop: 'name', label: '姓名', fixed: true, sortable: true, width: '100', formatter: this.stringFormater },
      { prop: 'sex', label: '性别', sortable: true, width: '120', formatter: this.sexFormater },
      { prop: 'departmentName', label: '工作单位', width: '180', sortable: true, formatter: this.stringFormater },
      { prop: 'workerType', label: '用工性质', width: '150', sortable: true, formatter: (row, column) => this.workTypeFormatter(store.state.sysconfigs.workerType, row, column) },
      { prop: 'state', label: '在职状态', width: '150', sortable: true, formatter: (row, column) => this.statusFormater(store.state.sysconfigs.state, row, column) },
      { prop: 'birthday', label: '出生时间', width: '150', sortable: true, formatter: this.dateFormater },
      { prop: 'nativePlace', label: '籍贯', width: '120', sortable: false, formatter: (row, column) => this.nativePlaceFormatter(store.state.sysconfigs.provinces, store.state.cities, row, column) },
      { prop: 'joinWorkTime', label: '参加工作时间', width: '140', sortable: false, formatter: this.dateFormater },
      { prop: 'createTime', label: '进本系统时间', width: '140', sortable: false, formatter: this.dateFormater },
      { prop: 'FtEducation', label: '学历学位', width: '120', sortable: false, formatter: (row, column) => this.categoryFormater(store.state.sysconfigs.FtEducation, row, column) },
      { prop: 'FtSchool', label: '毕业学校及专业', width: '160', sortable: false, formatter: this.stringFormater },
      { prop: 'ptj', label: '专业技术职务', width: '160', sortable: false, formatter: this.stringFormater },
      { prop: 'ptl', label: '专业技术级别', width: '160', sortable: false, formatter: (row, column) => this.categoryFormater(store.state.sysconfigs.ptl, row, column) },
      { prop: 'positions', label: '职务(岗位)', width: '120', sortable: false, formatter: (row, column) => this.positionFormater(store.state.sysconfigs.positions, row, column) },
      { prop: 'married', label: '婚姻情况', width: '120', sortable: false, formatter: (row, column) => this.marrageFormater(store.state.sysconfigs.married,row, column) },
      { prop: 'politicalStatus', label: '政治面貌',width:'120', sortable: false, formatter: (row, column)=> this.policyFormater(store.state.sysconfigs.politicalStatus,row, column) },
      { prop: 'joinPartyTime', label: '入党时间', width:'120',sortable: false, formatter: this.dateFormater }
    ]
  }

  getRetiredUsersColumns(){
    return [
      { prop: 'name', label: '姓名', fixed: true, sortable: true, width: '100', formatter: this.stringFormater },
      { prop: 'sex', label: '性别', sortable: true, width: '120', formatter: this.sexFormater },
      { prop: 'departmentName', label: '工作单位', width: '180', sortable: true, formatter: this.stringFormater },
      { prop: 'workerType', label: '用工性质', width: '150', sortable: true, formatter: (row, column) => this.workTypeFormatter(store.state.sysconfigs.workerType, row, column) },
      { prop: 'state', label: '在职状态', width: '150', sortable: true, formatter: (row, column) => this.statusFormater(store.state.sysconfigs.state, row, column) },
      { prop: 'birthday', label: '出生时间', width: '150', sortable: true, formatter: this.dateFormater },
      { prop: 'nativePlace', label: '籍贯', width: '120', sortable: false, formatter: (row, column) => this.nativePlaceFormatter(store.state.sysconfigs.provinces, store.state.cities, row, column) },
      { prop: 'joinWorkTime', label: '参加工作时间', width: '140', sortable: false, formatter: this.dateFormater },
      { prop: 'createTime', label: '进本系统时间', width: '140', sortable: false, formatter: this.dateFormater },
      { prop: 'FtEducation', label: '学历学位', width: '120', sortable: false, formatter: (row, column) => this.categoryFormater(store.state.sysconfigs.FtEducation, row, column) },
      { prop: 'FtSchool', label: '毕业学校及专业', width: '160', sortable: false, formatter: this.stringFormater },
      { prop: 'ptj', label: '专业技术职务', width: '160', sortable: false, formatter: this.stringFormater },
      { prop: 'ptl', label: '专业技术级别', width: '160', sortable: false, formatter: (row, column) => this.categoryFormater(store.state.sysconfigs.ptl, row, column) },
      { prop: 'positions', label: '职务(岗位)', width: '120', sortable: false, formatter: (row, column) => this.positionFormater(store.state.sysconfigs.positions, row, column) },
      { prop: 'married', label: '婚姻情况', width: '120', sortable: false, formatter: (row, column) => this.marrageFormater(store.state.sysconfigs.married,row, column) },
      { prop: 'retireTime', label: '退休时间',width:'120', sortable: false, formatter: this.dateFormater },
      { prop: 'workAge', label: '连续工龄', width:'120',sortable: false, formatter: this.stringFormater },
    ]
  }

  getTempUsersColumns(){
    return [
      { prop: 'name', label: '姓名', fixed: true, sortable: true, width: '100', formatter: this.stringFormater },
      { prop: 'sex', label: '性别', sortable: true, width: '120', formatter: this.sexFormater },
      { prop: 'departmentName', label: '工作单位', width: '180', sortable: true, formatter: this.stringFormater },
      { prop: 'workerType', label: '用工性质', width: '150', sortable: true, formatter: (row, column) => this.workTypeFormatter(store.state.sysconfigs.workerType, row, column) },
      { prop: 'state', label: '在职状态', width: '150', sortable: true, formatter: (row, column) => this.statusFormater(store.state.sysconfigs.state, row, column) },
      { prop: 'birthday', label: '出生时间', width: '150', sortable: true, formatter: this.dateFormater },
      { prop: 'nativePlace', label: '籍贯', width: '120', sortable: false, formatter: (row, column) => this.nativePlaceFormatter(store.state.sysconfigs.provinces, store.state.cities, row, column) },
      { prop: 'joinWorkTime', label: '参加工作时间', width: '140', sortable: false, formatter: this.dateFormater },
      { prop: 'createTime', label: '进本系统时间', width: '140', sortable: false, formatter: this.dateFormater },
      { prop: 'FtEducation', label: '学历学位', width: '120', sortable: false, formatter: (row, column) => this.categoryFormater(store.state.sysconfigs.FtEducation, row, column) },
      { prop: 'FtSchool', label: '毕业学校及专业', width: '160', sortable: false, formatter: this.stringFormater },
      { prop: 'ptj', label: '专业技术职务', width: '160', sortable: false, formatter: this.stringFormater },
      { prop: 'ptl', label: '专业技术级别', width: '160', sortable: false, formatter: (row, column) => this.categoryFormater(store.state.sysconfigs.ptl, row, column) },
      { prop: 'positions', label: '职务(岗位)', width: '120', sortable: false, formatter: (row, column) => this.positionFormater(store.state.sysconfigs.positions, row, column) },
      { prop: 'married', label: '婚姻情况', width: '120', sortable: false, formatter: (row, column) => this.marrageFormater(store.state.sysconfigs.married,row, column) },
      { prop: 'firstSignTime', label: '首次签订合同时间', width: '160', sortable: false, formatter: this.dateFormater },
      { prop: 'lastSignTime', label: '最新签订合同时间', width: '160', sortable: false, formatter: this.dateFormater },
    ]
  }

  getUsersColumns() {
    return [
      { prop: 'name', label: '姓名', fixed: true, sortable: true, width: '100', formatter: this.stringFormater },
      { prop: 'sex', label: '性别', sortable: true, width: '120', formatter: this.sexFormater },
      { prop: 'departmentName', label: '工作单位', width: '180', sortable: true, formatter: this.stringFormater },
      { prop: 'workerType', label: '用工性质', width: '150', sortable: true, formatter: (row, column) => this.workTypeFormatter(store.state.sysconfigs.workerType, row, column) },
      { prop: 'state', label: '在职状态', width: '150', sortable: true, formatter: (row, column) => this.statusFormater(store.state.sysconfigs.state, row, column) },
      { prop: 'birthday', label: '出生时间', width: '150', sortable: true, formatter: this.dateFormater },
      { prop: 'nativePlace', label: '籍贯', width: '120', sortable: true, formatter: (row, column) => this.nativePlaceFormatter(store.state.provinces, store.state.cities, row, column) },
      { prop: 'joinWorkTime', label: '参加工作时间', width: '140', sortable: true, formatter: this.dateFormater },
      { prop: 'createTime', label: '进本系统时间', width: '140', sortable: true, formatter: this.dateFormater },
      { prop: 'FtEducation', label: '学历学位', width: '120', sortable: true, formatter: (row, column) => this.categoryFormater(store.state.sysconfigs.FtEducation, row, column) },
      { prop: 'FtSchool', label: '毕业学校及专业', width: '160', sortable: true, formatter: this.stringFormater },
      { prop: 'ptj', label: '专业技术职务', width: '160', sortable: true, formatter: this.stringFormater },
      { prop: 'ptl', label: '专业技术级别', width: '160', sortable: true, formatter: (row, column) => this.categoryFormater(store.state.sysconfigs.ptl, row, column) },
      { prop: 'positions', label: '职务(岗位)', width: '120', sortable: true, formatter: (row, column) => this.positionFormater(store.state.sysconfigs.positions, row, column) },
      { prop: 'married', label: '婚姻情况', width: '120', sortable: true, formatter: (row, column) => this.marrageFormater(store.state.sysconfigs.married,row, column) }
    ]
  }

  getProfTechColumns() {
    return [
      { prop: 'level', label: '职称层级', sortable: true, width: '120', formatter: (row, column) => this.categoryFormater(store.state.sysconfigs.ptl, row, column) },
      { prop: 'positionlevel', label: '职称级别', sortable: true, width: '120', formatter: (row, column) => this.categoryFormater(store.state.sysconfigs.positionlevels_2, row, column) },
      { prop: 'techcate', label: '职称类别', width: '120', sortable: true, formatter:  (row, column) => this.categoryFormater(store.state.sysconfigs.techcategorylist, row, column)},
      { prop: 'name', label: '职称名称', width: '120', sortable: true, formatter: this.stringFormater },
      { prop: 'obtaintime', label: '资格获取时间', width: '150', sortable: true, formatter:this.stringFormater },
      { prop: 'employtime', label: '岗位聘任时间', width: '150', sortable: true, formatter: this.stringFormater },
      { prop: 'employunit', label: '聘任单位', width: '120', sortable: true, formatter: this.stringFormater },
      { prop: 'employcert', label: '聘任文号', width: '120', sortable: true, formatter: this.stringFormater }
    ]
  }

  hasRole(role){
    return (store.state.user.role.roles & role) == role
  }

  getSexName(sex) {
    if (sex == 1) {
      return '男'
    }
    else {
      return '女'
    }
  }

  getNameById(id, array) {
    for (var index in array) {
      if (array[index].id == id) {
        return array[index].name
      }
    }
    return ''
  }

  getEmptyText() {
    return '空'
  }

  marrageFormater(married,row, column) {
    for(var index in married){
      if(married[index].id == row[column.property]){
        return married[index].name
      }
    }
    return ''
  }

  stringFormater(row, column) {
    if (isNotEmpty(row, column)) {
      return row[column.property]
    }
    return ''
  }
  ageFormater(row, column) {
    if (isNotEmpty(row, column)) {
      var joinWorkTime = new Date(row[column.property])
      return new Date().getFullYear() - joinWorkTime.getFullYear()
    }
    return ''
  }
  dateFormater(row, column) {
    if (isNotEmpty(row, column)) {
      var joinWorkTime = new Date(row[column.property])
      return joinWorkTime.getFullYear() + '-' + zeroize(joinWorkTime.getMonth() + 1) //+ '-' + zeroize(joinWorkTime.getDate())
    }
    return ''
  }
  sexFormater(row, column) {
    for(var index in store.state.sysconfigs.sex){
      if(store.state.sysconfigs.sex[index].id == row[column.property]){
        return store.state.sysconfigs.sex[index].name
      }
    }
    return ''
  }
  schoolFormater(row, column) {
    if (row.FtSchool) {
      return row.FtSchool
    }
    if (row.PtSchool) {
      return row.PtSchool
    }
    return ''
  }
  statusFormater(employeeStates, row, column) {
    if (isNotEmpty(row, column)) {
      for (var index in employeeStates) {
        if (employeeStates[index].id == row.state) {
          return employeeStates[index].name
        }
      }
    }
    return ''
  }
  fieldFormater(row, column){

  }
  nativePlaceFormatter(provinces, cities, row, column) {
    if (isNotEmpty(row, column)) {
      var nativePlace = row.nativePlace
      var strArray = row.nativePlace.split(',')
      var strNativePlace = null
      for (var index in provinces) {
        if (provinces[index].code == strArray[0]) {
          strNativePlace = provinces[index].name
          break
        }
      }

      for (var index in cities) {
        if (cities[index].code == strArray[1]) {
          if (!strNativePlace) {
            strNativePlace = cities[index].name
          }
          else {
            strNativePlace = strNativePlace + cities[index].name
          }
          break
        }
      }
    }
    return strNativePlace
  }
  workTypeFormatter(worktypes, row, column) {
    if (isNotEmpty(row, column)) {
      //var worktypes = store.state.worktypes
      for (var index in worktypes) {
        if (worktypes[index].id == row.workerType) {
          return worktypes[index].name
        }
      }
    }
    return ''
  }

  stateFormatter(worktypes, row, column) {

  }
  departmentFormatter(row, column) {
    return row[column.property]
  }
  categoryFormater(categories, row, column) {
    if (isNotEmpty(row, column)) {
      for (var index in categories) {
        if (categories[index].id == row[column.property]) {
          return categories[index].name
        }
      }
    }
    return ''
  }
  policyFormater(policies, row, column) {
    if (isNotEmpty(row, column)) {
      //var policies = store.state.policies
      for (var index in policies) {
        if (policies[index].id == row.politicalStatus) {
          return policies[index].name
        }
      }
    }
    return ''
  }
  positionFormater(positions, row, column) {
    if (isNotEmpty(row, column)) {
      //var positions = store.state.positions
      var position = null
      var poss = row[column.property].split(',')
      if (poss) {
        for (var index in positions) {
          for (var posIndex in poss) {
            if (poss[posIndex] == positions[index].id) {
              if (position) {
                position = position + ',' + positions[index].name
              }
              else {
                position = positions[index].name
              }
            }
          }
        }
      }
      return position
    }
    return ''
  }

  parseData(dbData, userData,owner) {
    try {
      userData.id = dbData.id
      userData.kpis = JSON.parse(dbData.annualAssessment)
      userData.professionTechs = JSON.parse(dbData.technicalPosition)
      userData.parttimeEdus = JSON.parse(dbData.continueTrain)
      userData.trainings = JSON.parse(dbData.onlineWork)
      var relations = JSON.parse(dbData.socialReltaion)
      if(relations instanceof Array){
        userData.relations = relations
      }
      else{
        userData.relations = []
      }
      userData.extrainfo = JSON.parse(dbData.extraInfo)
      userData.userInfo = JSON.parse(dbData.baseInfo)
      userData.kpis = JSON.parse(dbData.annualAssessment)
      userData.projects = JSON.parse(dbData.projects)
      userData.races = JSON.parse(dbData.takePart)
      return true
    }
    catch (err) {
      owner.showErrorInfo("加载用户数据失败,请刷新后重试或联系管理员")
      console.log('important!parse data failed:' + err)
    }
    return false
  }

  decorateDate(time){
    if(time){
      if(time.split('-').length == 2){
        return time + '-01'
      }
    }
    return time
  }

  buildDbData(approveData,userData) {
    var positions = ''
    for (var pos in userData.userInfo.job.positions) {
      if (!positions) {
        positions = userData.userInfo.job.positions[pos]
      }
      else
        positions = positions + ',' + userData.userInfo.job.positions[pos]
    }

    var dbData = {
      annualAssessment: userData.kpis,
      projects: userData.projects,
      takePart: userData.races,
      technicalPosition: userData.professionTechs,
      continueTrain: userData.parttimeEdus,
      onlineWork: userData.trainings,
      socialReltaion: userData.relations,
      otherInfo: userData.extrainfo,
      resume: userData.userInfo.resumes,
      workerType: userData.userInfo.profile.workType,
      image:userData.userInfo.profile.image,
      state: userData.userInfo.profile.empState,
      name: userData.userInfo.profile.name,
      sex: userData.userInfo.profile.sex,
      idCard: userData.userInfo.profile.cert,
      nation: userData.userInfo.profile.national,
      joinWorkTime: this.decorateDate(userData.userInfo.profile.joinWorkTime),
      birthday: this.decorateDate(userData.userInfo.profile.birthday),
      nativePlace: userData.userInfo.profile.birthplace.province + ',' + userData.userInfo.profile.birthplace.city,
      politicalStatus: userData.userInfo.profile.policy,
      joinPartyTime: this.decorateDate(userData.userInfo.profile.ccptime),
      createTime: this.decorateDate(userData.userInfo.employsource.enterTime),
      source: userData.userInfo.employsource.channel,
      departmentId: userData.userInfo.employsource.depart[userData.userInfo.employsource.depart.length - 1],
      FtEducation: userData.userInfo.education.ftDegree,
      FtSchool: userData.userInfo.education.ftDiscipline,
      FtGraduateTime:userData.userInfo.education.FtGraduateTime,
      PtEducation: userData.userInfo.education.ptDegree,
      PtSchool: userData.userInfo.education.ptDiscipline,
      PtGraduateTime:userData.userInfo.education.PtGraduateTime,
      job: userData.userInfo.job.positionlevel,
      gwType: userData.userInfo.job.postType,
      positions: positions,
      positionType:userData.userInfo.job.positionType,
      tel: userData.extrainfo.extrabaseinfo.tel,
      phone: userData.extrainfo.extrabaseinfo.phone,
      baseInfo: userData.userInfo,
      extraInfo: userData.extrainfo,
      married: userData.extrainfo.extrabaseinfo.married
    }
    dbData.FtGraduateTime = this.decorateDate(dbData.FtGraduateTime)
    dbData.PtGraduateTime = this.decorateDate(dbData.PtGraduateTime)
    dbData.otherInfo.extrabaseinfo.firstsigntime = this.decorateDate(dbData.otherInfo.extrabaseinfo.firstsigntime)
    dbData.otherInfo.extrabaseinfo.lastsigntime = this.decorateDate(dbData.otherInfo.extrabaseinfo.lastsigntime)
    dbData.otherInfo.extrabaseinfo.retiretime = this.decorateDate(dbData.otherInfo.extrabaseinfo.retiretime)
    dbData.otherInfo.extrabaseinfo.fistengagetime = this.decorateDate(dbData.otherInfo.extrabaseinfo.fistengagetime)
    dbData.otherInfo.extrabaseinfo.engageLastTime = this.decorateDate(dbData.otherInfo.extrabaseinfo.engageLastTime)
    if (userData.id) {
      dbData.id = userData.id
    }

    var aprovalRetData = {
      approval:approveData.approval,
      reason:approveData.reason,
      person:dbData
    }
    if(approveData.approvalId){
      aprovalRetData.approvalId = approveData.approvalId
    }
    return aprovalRetData
  }

  getKpiYears() {
    var years = []
    var startYear = 2000
    var steps = 50
    for (var step = 0; step <= steps; step++) {
      var year = startYear + step
      years.push({
        id: year, 
        name: year
      })
    }
    return years
  }

  getDefaultUserQueryData(type) {
    return {
      type: type,
      conditions: [],
      // orders: {
      //   fields: 'name',
      //   desc: 0
      // },
      page: {
        count: 10,
        number: 0
      }
    }
  }

  updateUserData(approveData,userData, sucCallback, failedCallback) {
    if(!approveData){
      return
    }
    var postData = {
      approver:approveData.approver,
      reason:approveData.reason,
      person:userData
    }
    vue.http.post('/hr/person/update', JSON.stringify(postData)).then(response => {
      console.log("add response" + response);
      sucCallback(response)
    }, response => {
      failedCallback(response)
    })
  }

  delete(approveData,id, sucCallback, failedCallback) {
    if(!approveData){
      return
    }
    var postData = {
      approver:approveData.approver,
      reason:approveData.reason,
      id:id
    }
    vue.http.delete('/hr/person/delete',JSON.stringify(postData)).then(response => {
      console.log("query response" + response);
      sucCallback(response)
    }, response => {
      failedCallback(response)
    })
  }

  getUserData(id, sucCallback, failedCallback) {
    vue.http.post('/hr/person/get?id=' + id).then(response => {
      console.log("query response" + response);
      if(sucCallback)
        sucCallback(response)
    }, response => {
      failedCallback(response)
    })
  }

  queryUserData(queryData, sucCallback, failedCallback) {
    console.log('queryUserData @'+new Date())
    vue.http.post('/hr/person/query', JSON.stringify(queryData)).then(response => {
      console.log("query response:" + response+'@'+new Date());
      if (response.body.result == 1) {
        console.log('query user data id ' + JSON.stringify(response.body));
        sucCallback(response)
      }
      else
        failedCallback(response)
    }, response => {
      failedCallback(response)
    })
  }

  exportUserData(queryData,fileName, sucCallback, failedCallback) {
    vue.http.post('/hr/person/export/'+fileName, JSON.stringify(queryData)).then(response => {
      console.log("query response" + response);
      if (response.body.result == 1) {
        console.log('query user data id ' + JSON.stringify(response.body));
        sucCallback(response)
      }
      else
        failedCallback(response)
    }, response => {
      failedCallback(response)
    })
  }

  getDefaultRoleQueryData(){
    return {
      orders: {
        fields: 'name',
        desc: 0
      },
      page: {
        count: 20,
        number: 0
      }
    }
  }

  listRoles(queryData, sucCallback, failedCallback) {
    vue.http.post('/hr/user/role/list', JSON.stringify(queryData)).then(response => {
      console.log("list role response" + response);
      sucCallback(response)
    }, response => {
      failedCallback(response)
    })
  }

  getDashData(sucCallback, failedCallback) {
    var url = '/hr/user/getHome'
    vue.http.post(url).then(response => {
      console.log("get home response:" + response);
      if(response.body.result == 1 && sucCallback)
        sucCallback(response)
      else if (failedCallback)
        failedCallback(response)
    }, response => {
      if(failedCallback)
        failedCallback(response)
    })
  }

  ssoLogin(token, sucCallback, failedCallback) {
    var url = '/hr/user/ssoLogin?token='+token
    vue.http.post(url).then(response => {
      console.log("login response:" + response);
      sucCallback(response)
    }, response => {
      failedCallback(response)
    })
  }

  login(user,pwd, sucCallback, failedCallback) {
    var url = '/hr/user/login?user='+user+'&password='+pwd
    vue.http.post(url).then(response => {
      console.log("login response:" + JSON.stringify(response));
      sucCallback(response)
    }, response => {
      failedCallback(response)
    })
  }

  showErrorInfo(owner,info){
    owner.$message({
      message: info,
      type: 'error'
    });
  }

  showSucInfo(owner,info){
    owner.$message({
      message: info,
      type: 'success'
    });
  }

  sendSmsPwd(user,sucCallback, failedCallback){
    var para = "user="+user
    vue.http.post('/hr/user/auth/send?'+para).then(response => {
      console.log("change auth/send:" + response);
      sucCallback(response)
    }, response => {
      failedCallback(response)
    })
  }

  smsAuth(user,code,sucCallback, failedCallback){
    var para = "user="+user+"&code="+code
    vue.http.post('/hr/user/auth/check?'+para).then(response => {
      console.log("send auth/check:" + response);
      sucCallback(response)
    }, response => {
      failedCallback(response)
    })
  }

  changePwd(user,oldPWd,pwd,smsAuth, sucCallback, failedCallback) {
    var para = smsAuth?"user="+user+"&code="+oldPWd+"&pwd="+pwd
                      :"user="+user+"&oldPassword="+oldPWd+"&newPassword="+pwd
    var url = smsAuth?'/hr/user/auth/resetPwd?'
                      :'/hr/user/changePassword?'
    vue.http.post(url+para).then(response => {
      console.log("change password response:" + response);
      sucCallback(response)
    }, response => {
      failedCallback(response)
    })
  }

  addRoles(role, sucCallback, failedCallback) {
    vue.http.post('/hr/user/role/add', JSON.stringify(role)).then(response => {
      console.log("add role response" + response);
      sucCallback(response)
    }, response => {
      failedCallback(response)
    })
  }

  updateRole(queryData, sucCallback, failedCallback) {
    vue.http.post('/hr/user/role/update', JSON.stringify(queryData)).then(response => {
      console.log("update role response" + response);
      sucCallback(response)
    }, response => {
      failedCallback(response)
    })
  }

  deleteRole(id, sucCallback, failedCallback) {
    vue.http.post('/hr/user/role/delete?id='+id).then(response => {
      console.log("delete role response" + response);
      sucCallback(response)
    }, response => {
      failedCallback(response)
    })
  }

  deleteConf(owner,confirmCb,cancelCb){
    owner.$confirm('此操作将永久删除改数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        if(confirmCb){
          confirmCb()
        }
      }).catch(() => {
        if(cancelCb){
          cancelCb()
        }
      });
  }

  getDefaultSelectedUser() {
    return {
      data: {
        id: 0,
        trainings: [],
        parttimeEdus: [],
        professionTechs: [],
        races: [],
        projects: [],
        kpis: [],
        userInfo: {
          profile: {
            empState: 1,
            workType: 1,
            national: 1,
            policy: 1,
            birthplace: {
              province: 110000,
              city: 110100
            },
            name: '',
            birthday: '',
            ccptime: '',
            joinWorkTime:'',
            sex: '1',
            cert: ''
          },
          employsource: {
            channel: 1,
            depart: [],
            enterTime: ''
          },
          job: {
            postType: 1,
            positionlevel: 1,
            positions: [],
            postCate: 1
          },
          resumes: []
        },
        relations: [],
        extrainfo: {
          extrabaseinfo: {
            fistengagetime: '',
            engageLastTime: '',
            skillworkerdepart: '',
            skillworkerEngageTime: '',
            retiretime: '',
            workage: 0,
            firstsigntime: '',
            lastsigntime: '',
            lefttime: '',
            married: '0',
            domicile: '',
            docloc: '',
            phone: '',
            tel: '',
            qq: '',
            likes: '',
            address: ''
          },
          rewards: []
        }
      }
    }
  }

  deepCopy(o, c) {
    var c = c || {};
    for (var i in o) {
      if (typeof o[i] === "object") {
        if (o[i].constructor === Array) {
          c[i] = [];
        } else {
          c[i] = {};
        }
        this.deepCopy(o[i], c[i]);
      } else {
        c[i] = o[i];
      }
    }
    return c;
  }

  str2date(str){
    return new Date(Date.parse(str.replace(/-/g,  "/")));
  }

  getPreMonth(date) {
    var arr = date.split('-');
    var year = arr[0]; //获取当前日期的年份
    var month = arr[1]; //获取当前日期的月份
    var day = arr[2]; //获取当前日期的日
    var days = new Date(year, month, 0);
    days = days.getDate(); //获取当前日期中月的天数
    var year2 = year;
    var month2 = parseInt(month) - 1;
    if (month2 == 0) {
        year2 = parseInt(year2) - 1;
        month2 = 12;
    }
    var day2 = day;
    var days2 = new Date(year2, month2, 0);
    days2 = days2.getDate();
    if (day2 > days2) {
        day2 = days2;
    }
    if (month2 < 10) {
        month2 = '0' + month2;
    }
    var t2 = year2 + '-' + month2 + '-' + day2;
    return t2;
}

  date2str(date,fmt){        
      var o = {         
      "M+" : date.getMonth()+1, //月份         
      "d+" : date.getDate(), //日         
      "h+" : date.getHours()%12 == 0 ? 12 : date.getHours()%12, //小时         
      "H+" : date.getHours(), //小时         
      "m+" : date.getMinutes(), //分         
      "s+" : date.getSeconds(), //秒         
      "q+" : Math.floor((date.getMonth()+3)/3), //季度         
      "S" : date.getMilliseconds() //毫秒         
      }         
      var week = {         
      "0" : "/u65e5",         
      "1" : "/u4e00",         
      "2" : "/u4e8c",         
      "3" : "/u4e09",         
      "4" : "/u56db",         
      "5" : "/u4e94",         
      "6" : "/u516d"        
      };         
      if(/(y+)/.test(fmt)){         
          fmt=fmt.replace(RegExp.$1, (date.getFullYear()+"").substr(4 - RegExp.$1.length));         
      }         
      if(/(E+)/.test(fmt)){         
          fmt=fmt.replace(RegExp.$1, ((RegExp.$1.length>1) ? (RegExp.$1.length>2 ? "/u661f/u671f" : "/u5468") : "")+week[date.getDay()+""]);         
      }         
      for(var k in o){         
          if(new RegExp("("+ k +")").test(fmt)){         
              fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));         
          }         
      }         
      return fmt
  }
}

function zeroize(value, length) {
  if (!length) length = 2;
  value = String(value);
  for (var i = 0, zeros = ''; i < (length - value.length); i++) {
    zeros += '0';
  }
  return zeros + value;
}